<template>
  <div class="profile-settings">
    <div class="page-header">
      <h2>个人信息设置</h2>
    </div>

    <div class="profile-layout">
      <!-- 左侧：基本信息 -->
      <div class="left-column">
        <div class="profile-section">
          <h3>基本信息</h3>
          <div class="profile-card">
            <div class="avatar-section">
              <div class="avatar" @click="showAvatarDialog = true">
                <img :src="expertInfo.avatar" :alt="expertInfo.name" v-if="expertInfo.avatar">
                <span v-else>{{ expertInfo.name.charAt(0) }}</span>
                <div class="avatar-overlay">
                  <i class="fas fa-camera"></i>
                </div>
              </div>
              <div class="avatar-info">
                <p class="avatar-name">{{ expertInfo.name }}</p>
                <p class="avatar-title">{{ expertInfo.title }}</p>
                <el-button type="primary" size="small" @click="showAvatarDialog = true">
                  <i class="fas fa-camera"></i> 更换头像
                </el-button>
              </div>
            </div>
            
            <form @submit.prevent="saveProfile" class="profile-form">
              <div class="form-row">
                <div class="form-group">
                  <label>姓名</label>
                  <el-input v-model="expertInfo.name" placeholder="请输入姓名" />
                </div>
                <div class="form-group">
                  <label>职称</label>
                  <el-input v-model="expertInfo.title" placeholder="请输入职称" />
                </div>
              </div>
              
              <div class="form-row">
                <div class="form-group">
                  <label>院校</label>
                  <el-input v-model="expertInfo.institution" placeholder="请输入所在院校" />
                </div>
                <div class="form-group">
                  <label>从业经验</label>
                  <div class="experience-input">
                    <el-input-number 
                      v-model="expertInfo.experience" 
                      :min="0" 
                      :max="50"
                      controls-position="right"
                    />
                    <span class="unit">年</span>
                  </div>
                </div>
              </div>
              
              <div class="form-group">
                <label>专业领域</label>
                <el-input
                  v-model="expertInfo.specialty"
                  type="textarea"
                  :rows="2"
                  placeholder="例如：蔬菜种植、果树栽培、土壤改良"
                />
              </div>
              
              <div class="form-group">
                <label>个人简介</label>
                <el-input
                  v-model="expertInfo.description"
                  type="textarea"
                  :rows="4"
                  placeholder="请简要介绍您的专业背景和工作经验..."
                />
              </div>
            </form>
          </div>
        </div>

        <!-- 预约设置 -->
        <div class="profile-section">
          <h3>预约设置</h3>
          <div class="settings-card">
            <div class="setting-item">
              <label class="setting-label">
                <el-switch v-model="expertInfo.settings.onlineQA" />
                <span>开启线上答疑</span>
              </label>
            </div>
            <div class="setting-item">
              <label class="setting-label">
                <el-switch v-model="expertInfo.settings.offlineAppointment" />
                <span>开启线下预约</span>
              </label>
            </div>
            <div class="setting-item">
              <label class="setting-label">单次咨询时长限制</label>
              <el-select v-model="expertInfo.settings.sessionDuration" style="width: 120px;">
                <el-option label="30分钟" value="30" />
                <el-option label="45分钟" value="45" />
                <el-option label="60分钟" value="60" />
                <el-option label="90分钟" value="90" />
              </el-select>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：服务统计和评分 -->
      <div class="right-column">
        <!-- 服务统计 -->
        <div class="profile-section">
          <h3>服务统计</h3>
          <div class="stats-card">
            <div class="stats-grid">
              <div class="stat-item">
                <div class="stat-icon">
                  <i class="fas fa-comments"></i>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ expertInfo.stats.consultations }}</div>
                  <div class="stat-label">咨询服务</div>
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-icon">
                  <i class="fas fa-chart-line"></i>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ expertInfo.stats.successRate }}%</div>
                  <div class="stat-label">解决率</div>
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-icon">
                  <i class="fas fa-clock"></i>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ expertInfo.stats.avgResponse }}</div>
                  <div class="stat-label">平均响应(分钟)</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 评分信息 -->
        <div class="profile-section">
          <h3>评分信息</h3>
          <div class="rating-card">
            <div class="rating-overview">
              <div class="rating-score">
                <span class="score">{{ expertInfo.rating.score }}</span>
                <div class="stars">
                  <i 
                    v-for="n in 5" 
                    :key="n"
                    class="fas fa-star"
                    :class="{ 'active': n <= Math.floor(expertInfo.rating.score), 'half': n === Math.ceil(expertInfo.rating.score) && expertInfo.rating.score % 1 !== 0 }"
                  ></i>
                </div>
                <span class="rating-count">{{ expertInfo.rating.count }}条评价</span>
              </div>
            </div>
            
            <div class="rating-details">
              <div class="rating-item" v-for="item in ratingDetails" :key="item.label">
                <span class="rating-label">{{ item.label }}</span>
                <div class="rating-bar">
                  <div class="rating-progress" :style="{ width: item.percentage + '%' }"></div>
                </div>
                <span class="rating-percentage">{{ item.percentage }}%</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 保存按钮 -->
    <div class="action-buttons">
      <el-button @click="resetForm">重置</el-button>
      <el-button type="primary" @click="saveProfile">保存更改</el-button>
    </div>

    <!-- 更换头像弹窗 -->
    <el-dialog
      v-model="showAvatarDialog"
      title="更换头像"
      width="500px"
      center
    >
      <div class="avatar-dialog-content">
        <!-- 当前头像预览 -->
        <div class="current-avatar-section">
          <h4>当前头像</h4>
          <div class="current-avatar">
            <img :src="expertInfo.avatar" :alt="expertInfo.name" v-if="expertInfo.avatar">
            <div v-else class="avatar-placeholder">
              {{ expertInfo.name.charAt(0) }}
            </div>
          </div>
        </div>

        <!-- 上传新头像 -->
        <div class="upload-section">
          <h4>上传新头像</h4>
          <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleAvatarUpload"
            accept="image/jpeg,image/png,image/jpg"
          >
            <div v-if="uploading" class="uploading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>上传中...</span>
            </div>
            <div v-else-if="newAvatarUrl" class="avatar-preview">
              <img :src="newAvatarUrl" alt="新头像预览" />
              <div class="preview-overlay">
                <i class="fas fa-check"></i>
              </div>
            </div>
            <div v-else class="upload-placeholder">
              <i class="fas fa-cloud-upload-alt"></i>
              <div class="upload-text">点击上传头像</div>
              <div class="upload-hint">支持 JPG、PNG 格式，大小不超过 2MB</div>
            </div>
          </el-upload>
        </div>

        <!-- 默认头像选择 -->
        <div class="default-avatars-section">
          <h4>选择默认头像</h4>
          <div class="default-avatars">
            <div
              v-for="avatar in defaultAvatars"
              :key="avatar"
              class="default-avatar"
              :class="{ selected: newAvatarUrl === avatar }"
              @click="selectDefaultAvatar(avatar)"
            >
              <img :src="avatar" alt="默认头像" />
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAvatarChange">取消</el-button>
          <el-button type="primary" :disabled="!newAvatarUrl" @click="confirmAvatarChange">
            确认更换
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'

// 响应式数据
const showAvatarDialog = ref(false)
const uploading = ref(false)
const newAvatarUrl = ref('')
const uploadRef = ref()

// 默认头像列表
const defaultAvatars = ref([
  'https://images.unsplash.com/photo-1582750433449-648ed127bb54?w=150&h=150&fit=crop&crop=face',
  'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=150&h=150&fit=crop&crop=face',
  'https://images.unsplash.com/photo-1560250097-0b93528c311a?w=150&h=150&fit=crop&crop=face',
  'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&crop=face'
])

// 专家信息数据
const originalExpertInfo = {
  name: '张教授',
  title: '农业种植专家',
  institution: '中国农业大学',
  specialty: '蔬菜种植、果树栽培、土壤改良',
  experience: 15,
  description: '长期从事农业种植技术研究，在蔬菜和果树种植方面有丰富的实践经验。曾参与多个国家级农业科研项目，发表学术论文20余篇。',
  avatar: 'https://images.unsplash.com/photo-1582750433449-648ed127bb54?w=150&h=150&fit=crop&crop=face',
  stats: {
    consultations: 256,
    successRate: 95,
    avgResponse: 30
  },
  rating: {
    score: 4.8,
    count: 128
  },
  settings: {
    onlineQA: true,
    offlineAppointment: true,
    sessionDuration: '45'
  }
}

const expertInfo = ref({...originalExpertInfo})

// 评分详情数据
const ratingDetails = ref([
  { label: '5星', percentage: 85 },
  { label: '4星', percentage: 12 },
  { label: '3星', percentage: 2 },
  { label: '2星', percentage: 1 },
  { label: '1星', percentage: 0 }
])

// 头像上传相关方法
const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarUpload = async (options) => {
  const { file } = options
  uploading.value = true

  try {
    // 模拟上传过程
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 在实际项目中，这里应该调用上传API
    // const formData = new FormData()
    // formData.append('avatar', file)
    // const response = await uploadAvatarAPI(formData)
    // newAvatarUrl.value = response.data.url
    
    // 这里使用本地URL预览
    const reader = new FileReader()
    reader.onload = (e) => {
      newAvatarUrl.value = e.target.result
      uploading.value = false
    }
    reader.readAsDataURL(file)
  } catch (error) {
    ElMessage.error('头像上传失败，请重试')
    uploading.value = false
  }
}

const selectDefaultAvatar = (avatarUrl) => {
  newAvatarUrl.value = avatarUrl
}

const confirmAvatarChange = () => {
  if (newAvatarUrl.value) {
    expertInfo.value.avatar = newAvatarUrl.value
    ElMessage.success('头像更换成功！')
    showAvatarDialog.value = false
    resetAvatarDialog()
  }
}

const cancelAvatarChange = () => {
  showAvatarDialog.value = false
  resetAvatarDialog()
}

const resetAvatarDialog = () => {
  newAvatarUrl.value = ''
  uploading.value = false
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 其他方法
const saveProfile = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('个人信息更新成功！')
  } catch (error) {
    ElMessage.error('保存失败，请重试')
  }
}

const resetForm = async () => {
  try {
    await ElMessageBox.confirm('确定要重置所有更改吗？', '提示', {
      type: 'warning'
    })
    expertInfo.value = {...originalExpertInfo}
    ElMessage.success('重置成功')
  } catch {
    // 用户取消操作
  }
}
</script>

<style scoped>
.profile-settings {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.profile-layout {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 30px;
  align-items: start;
}

.profile-section {
  margin-bottom: 30px;
}

.profile-section h3 {
  margin-bottom: 15px;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.profile-card,
.stats-card,
.rating-card,
.settings-card,
.quick-actions-card {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  border: 1px solid #f0f0f0;
}

/* 头像区域 */
.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 25px;
  padding-bottom: 25px;
  border-bottom: 1px solid #f0f0f0;
}

.avatar {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4CAF50, #2E7D32);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
  font-weight: bold;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.avatar:hover .avatar-overlay {
  opacity: 1;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-info {
  flex: 1;
}

.avatar-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.avatar-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
}

/* 头像弹窗样式 */
.avatar-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.current-avatar-section,
.upload-section,
.default-avatars-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.current-avatar-section h4,
.upload-section h4,
.default-avatars-section h4 {
  color: #333;
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.current-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #f0f0f0;
}

.current-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #4CAF50, #2E7D32);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
}

/* 上传区域 */
.avatar-uploader {
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #4CAF50;
}

.uploading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #666;
}

.avatar-preview {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(76, 175, 80, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #8c939d;
}

.upload-placeholder i {
  font-size: 48px;
  color: #c0c4cc;
}

.upload-text {
  font-size: 16px;
  color: #333;
}

.upload-hint {
  font-size: 12px;
  color: #999;
}

/* 默认头像选择 */
.default-avatars {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.default-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.default-avatar:hover {
  border-color: #4CAF50;
  transform: scale(1.05);
}

.default-avatar.selected {
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.default-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 其他样式保持不变... */
.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.experience-input {
  display: flex;
  align-items: center;
  gap: 10px;
}

.unit {
  color: #666;
  font-size: 14px;
}

/* 统计卡片样式 */
.stats-grid {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  background: #e8f5e9;
  transform: translateY(-2px);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: linear-gradient(135deg, #4CAF50, #66BB6A);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #2E7D32;
  margin-bottom: 4px;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

/* 评分卡片样式 */
.rating-overview {
  margin-bottom: 20px;
}

.rating-score {
  text-align: center;
}

.score {
  font-size: 48px;
  font-weight: bold;
  color: #FF9800;
  display: block;
  line-height: 1;
}

.stars {
  margin: 12px 0;
  display: flex;
  justify-content: center;
  gap: 4px;
}

.stars .fa-star {
  color: #ddd;
  font-size: 20px;
}

.stars .fa-star.active {
  color: #FFC107;
}

.stars .fa-star.half {
  background: linear-gradient(90deg, #FFC107 50%, #ddd 50%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.rating-count {
  color: #666;
  font-size: 14px;
}

.rating-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.rating-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.rating-label {
  width: 40px;
  color: #666;
  font-size: 14px;
}

.rating-bar {
  flex: 1;
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.rating-progress {
  height: 100%;
  background: linear-gradient(90deg, #FFC107, #FF9800);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.rating-percentage {
  width: 40px;
  color: #666;
  font-size: 12px;
  text-align: right;
}

/* 设置卡片样式 */
.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-label {
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 600;
  color: #333;
}

/* 快捷操作 */
.quick-actions-card {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.quick-action-btn {
  width: 100%;
  justify-content: flex-start;
  padding: 12px 16px;
}

.quick-action-btn i {
  margin-right: 8px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 40px;
  padding-top: 30px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .profile-layout {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .right-column {
    order: -1;
  }
}

@media (max-width: 768px) {
  .profile-settings {
    padding: 16px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .stat-item {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .default-avatars {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>